package com.hmyd.hmyd_android.ui;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.adapter.BillRedeemHistoryAdapter;
import com.hmyd.hmyd_android.adapter.WithdrawalsHistoryListAdapter;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dto.Deposit;
import com.hmyd.hmyd_android.dto.Page;
import com.hmyd.hmyd_android.dto.RedemptionHistory;
import com.hmyd.hmyd_android.dto.WithdrawHistory;
import com.hmyd.hmyd_android.utils.MyToast;
import com.hmyd.hmyd_android.utils.Utils;
import com.hmyd.hmyd_android.view.listview.XListView;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;

import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.TextView;

/**
 * 取款/票据赎回记录
 *
 */
@ContentView(R.layout.activity_withdrawals_history_list)
public class WithdrawalsHistoryListActivity extends BasicListActivity {
	@ViewInject(R.id.home_title)
	public View home_title;
	@ViewInject(R.id.home_title_txt)
	public TextView home_title_txt;
	@ViewInject(R.id.home_right)
	public TextView home_right;
	
	@ViewInject(R.id.list)
	private XListView mList;
	private WithdrawalsHistoryListAdapter mWithdrawalsHistoryListAdapter;
	private BillRedeemHistoryAdapter  mBillRedeemHistoryAdapter;
	
	@ViewInject(R.id.bottom_blank)
	private TextView bottom_blank;
	
	@ViewInject(R.id.total)
	private TextView mTotal;
	
	private final int REFRESH = 1;
	private final int LOADMORE = 2;
	private final int TOTALAMOUNT = 3;
	private final int BILL_REDEEM_RECORD_REFRESH = 4; // 赎回记录刷新记录
	private final int BILL_REDEEM_RECORD_LOADMORE = 5; // 赎回记录加载更多
	private final int BILL_REDEEM_TOTAL_AMOUNT = 6; // 赎回总金额
	
	protected boolean hasMore = false;
	private String cursorId;
	
	private int isFromBill;
	private List<RedemptionHistory> redemptionHistory = new ArrayList<RedemptionHistory>(); // 赎回记录
	
	private List<WithdrawHistory> listData = new ArrayList<WithdrawHistory>();
	
	/**
	 * 获取网络数据
	 */
	private void onRequest(){
		onRequest(REFRESH, UrlConstant.WITHDRAWHISTORY, HttpMethod.GET, null);
		onRequest(TOTALAMOUNT, UrlConstant.WITHDRAWTOTALAMOUNT, HttpMethod.GET, null);
	};
	
	/**
	 * 票据赎回记录请求
	 */
	private void onBillRequest() {
		onRequest(BILL_REDEEM_RECORD_REFRESH, UrlConstant.BILL_REDEEM_RECORD, HttpMethod.POST, null);
		onRequest(BILL_REDEEM_TOTAL_AMOUNT, UrlConstant.BILL_REDEEM_TOTAL_AMOUNT, HttpMethod.GET, null);
	}
	
	public XListView getXList() {
		return mList;
	}
	
	@Override
	protected void setParams() {
		home_title.setOnTouchListener(touch);
		mList.setPullRefreshEnable(true); // 允许下拉刷新
		mList.setPullLoadEnable(false); // 禁止加载更多
		mList.setAutoLoadEnable(false); // 禁止自动加载
		mList.setXListViewListener(this);// 加载监听
		
		isFromBill = this.getIntent().getIntExtra("isFromBill", 0);
		if(isFromBill == 1) {
			mBillRedeemHistoryAdapter = new BillRedeemHistoryAdapter(this, redemptionHistory);
			mList.setAdapter(mBillRedeemHistoryAdapter);
			home_title_txt.setText(getResources().getString(R.string.bill_redeem_record)); // 顶部文字变更
			bottom_blank.setText(getString(R.string.bill_accumulate_amount)); // 底部文字变更
			onBillRequest();
		} else {
			// 两像素的描边
			mList.setDividerHeight(2);
			mWithdrawalsHistoryListAdapter = new WithdrawalsHistoryListAdapter(this, listData);
			mList.setAdapter(mWithdrawalsHistoryListAdapter);
			home_title_txt.setText(getResources().getString(R.string.assets_cash_detail));
			onRequest();
		}
		
	}
	
	@Override
	protected void leftButton() {
		AppBasic.getInstance().finishCurrentActivity();
	}
	
	@Override
	public void onRefresh() {
		super.onRefresh();
		if(isFromBill == 1) {
			onRequest(BILL_REDEEM_RECORD_REFRESH, UrlConstant.BILL_REDEEM_RECORD, HttpMethod.POST, null);
		} else {
			onRequest(REFRESH, UrlConstant.WITHDRAWHISTORY, HttpMethod.GET, null);
			onRequest(TOTALAMOUNT, UrlConstant.WITHDRAWTOTALAMOUNT, HttpMethod.GET, null);
		}
	}
	
	@Override
	public void onLoadMore() {
		super.onLoadMore();
		RequestParams params = new RequestParams();
		params.addBodyParameter("lastCursor", cursorId);
		if(isFromBill == 1) {
			onRequest(BILL_REDEEM_RECORD_LOADMORE, UrlConstant.BILL_REDEEM_RECORD, HttpMethod.POST, params);
		} else {
			onRequest(LOADMORE, UrlConstant.WITHDRAWHISTORY, HttpMethod.GET, params);
		}
	}

	public void onPostSuccess(int postId, String result) {
		super.onPostSuccess(postId, result);
		Gson gson = new Gson();
		switch (postId) {
		case TOTALAMOUNT:
			java.lang.reflect.Type type = new TypeToken<Deposit>() {}.getType();
			Deposit deposit = gson.fromJson(result, type);
			mTotal.setText(Utils.amountConversionFormat(deposit.totalAmount));
			break;
		case BILL_REDEEM_TOTAL_AMOUNT:
			try {
				JSONObject json = new JSONObject(result);
				String amount = json.getString("totalAmount");
				mTotal.setText(amount);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			break;
		case BILL_REDEEM_RECORD_REFRESH:
			Type type2 = new TypeToken<Page<RedemptionHistory>>() {
			}.getType();
			Page<RedemptionHistory> redemptionHistorys = gson.fromJson(result, type2);
			hasMore = redemptionHistorys.hasMore;
			if(redemptionHistorys!=null && redemptionHistorys.records!=null){
				redemptionHistory.clear();
				redemptionHistory.addAll(redemptionHistorys.records);
				if(redemptionHistory.size()>0){
					cursorId = String.valueOf(redemptionHistory.get(redemptionHistory.size()-1).createdTime);
				}else{
					cursorId = null;
				}
				mBillRedeemHistoryAdapter.notifyDataSetChanged();
			}
			break;
		case BILL_REDEEM_RECORD_LOADMORE:
			Type type3 = new TypeToken<Page<RedemptionHistory>>() {
			}.getType();
			Page<RedemptionHistory> redemptionHistorys2 = gson.fromJson(result, type3);
			hasMore = redemptionHistorys2.hasMore;
			
			if(redemptionHistorys2!=null && redemptionHistorys2.records!=null){
				redemptionHistory.addAll(redemptionHistorys2.records);
				if(redemptionHistory.size()>0){
					cursorId = String.valueOf(redemptionHistory.get(redemptionHistory.size()-1).createdTime);
				}else{
					cursorId = null;
				}
				mBillRedeemHistoryAdapter.notifyDataSetChanged();
			}
			break;
		case REFRESH:
		case LOADMORE:
			java.lang.reflect.Type type4 = new TypeToken<Page<WithdrawHistory>>() {}.getType();
			Page<WithdrawHistory> page = gson.fromJson(result, type4);
			hasMore = page.hasMore;
			
			if(page!=null && page.records!=null){
				switch (postId) {
				case REFRESH:
					listData.clear();
					listData.addAll(page.records);
					break;
				case LOADMORE:
					listData.addAll(page.records);
					break;
				default:
					break;
				}
				
				if(listData.size()>0){
					cursorId = String.valueOf(listData.get(listData.size()-1).createdTime);
				}else{
					cursorId = null;
				}
				
				mWithdrawalsHistoryListAdapter.notifyDataSetChanged();
			}
			break;
		default:
			break;
		}
		
		if(getXList()!=null && hasMore){
			getXList().setPullLoadEnable(true);
		}else if(getXList()!=null && !hasMore){
			getXList().setPullLoadEnable(false);
		}
		
	}

	public void onPostFailure(int postId, String msg) {
		super.onPostFailure(postId, msg);
		
		switch (postId) {
		case BILL_REDEEM_TOTAL_AMOUNT:
			MyToast.showHMToast(this, false, "获取赎回总金额失败,"+msg);
			break;

		default:
			break;
		}
		
		if(getXList()!=null && hasMore){
			getXList().setPullLoadEnable(true);
		}else if(getXList()!=null && !hasMore){
			getXList().setPullLoadEnable(false);
		}
	}

	@Override
	protected void rightButton() {
		
	}

}
